package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    private R handlerException(SQLIntegrityConstraintViolationException exception) {
        log.error(exception.getMessage(), exception);
        if (exception.getMessage().contains("Duplicate entry")) {
            String errorMessage = exception.getMessage().split(" ")[2];
            return R.error(errorMessage+"已存在");
        }
        return R.error("对不起，服务器异常，请稍后重试！");

    }
    @ExceptionHandler(CustomException.class)
    public R handlerException(CustomException exception){
        log.error(exception.getMessage(),exception);
        return  R.error(exception.getMessage());
    }
}
